const express = require('express')
const returnUtil = require('../util/return')
const router = express.Router()
const msgModel = require('../model/Msg')
const errorConst = require('../const/error')

let routerHelper = (function () {
  return {
    addHandler: async function (req, res, next) {
      if (!req.session.loginUser) {
        return returnUtil.error(res, errorConst.needLogin)
      }
      let title = req.body.msgTitle
      let content = req.body.msgContent
      let data = {title: title, content: content, user_id: req.session.loginUser.id}
      let flag = await msgModel.createByData(data)
      if (flag) {
        return returnUtil.success(res)
      }

      return returnUtil.error(res)
    },
    updateHandler: async function (req, res, next) {
      if (!req.session.loginUser) {
        return returnUtil.error(res, errorConst.needLogin)
      }
      let id = req.body.id
      let title = req.body.title
      let content = req.body.content
      let data = {title: title, content: content, id: id}
      let flag = await msgModel.updateByData(data)
      if (flag) {
        return returnUtil.success(res)
      }

      return returnUtil.error(res)
    },
    listHandler: async function (req, res, next) {
      let userId = req.query.user_id
      let msgList = await msgModel.getListByUserId(userId)
      return returnUtil.success(res, msgList)
    },
    infoHandler: async function (req, res, next) {
      let id = req.query.id
      let info = await msgModel.getInfoById(id)
      return returnUtil.success(res, info)
    }
  }
})()

router.post('/add', routerHelper.addHandler)
router.post('/update', routerHelper.updateHandler)
router.get('/list', routerHelper.listHandler)
router.get('/info', routerHelper.infoHandler)

module.exports = router
